package com.store.web.security;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.views.velocity.components.SetDirective;

import com.opensymphony.xwork2.ActionSupport;
import com.ross.web.DTO.ProductDTO;
import com.ross.web.dao.AuditLogDAO;
import com.ross.web.dao.UsersDAO;
import com.ross.web.domain.AuditLog;
import com.ross.web.domain.Users;
import com.ross.web.util.DateUtil;
import com.ross.web.util.SessionLogout;

public class AuditLogAction extends ActionSupport {
	
	private List<Users> userList;
	private List<AuditLog> auditlogList;
	private List<ProductDTO> productList = new ArrayList<ProductDTO>();
	private int al_id;
	private int dispMode;
	private AuditLog auditLog;
	private Date startDate;
	private Date endDate;
	private String loggedUser;
	private Double grandTotal;
	boolean getToday;
	private InputStream fileStream;
	
	HttpServletRequest request = ServletActionContext.getRequest();
	private SessionLogout sessionLogout = new SessionLogout();
	
	UsersDAO usersDAO = new UsersDAO();
	AuditLogDAO auditLogDAO = new AuditLogDAO();
	
	public String goToAuditLogAction(){
		
		if (sessionLogout.SessionExpired()) {
			addActionMessage("Session already expired");
			return "sessionExpired";
		}
		
		userList = usersDAO.getAllUsers();
		setDispMode(1);
		
		if(request.getSession().getAttribute("auditlogList") != null){
			auditlogList = (List) request.getSession().getAttribute("auditlogList");
		}
		
		if(request.getSession().getAttribute("grandTotal") != null){
			grandTotal = (Double) request.getSession().getAttribute("grandTotal");
		}else{
			grandTotal = (double) 0;
		}
		
		request.getSession().setAttribute("userList", userList);
		request.getSession().setAttribute("auditlogList", auditlogList);
		request.getSession().setAttribute("grandTotal", grandTotal);
		
		return SUCCESS;
	}
	
	public String searchAuditLogsAction(){
		
		if (sessionLogout.SessionExpired()) {
			addActionMessage("Session already expired");
			return "sessionExpired";
		}
		try{
		List<AuditLog> alList;
		auditlogList = new ArrayList<AuditLog>();
		String logDate;
		grandTotal = (double) 0;
		if(getToday){
			startDate = new Date();
			endDate = new Date();
		}
		Long oldstartdate = startDate.getTime();
		while (DateUtil.isDateFromDateToEqual(startDate, endDate) != 0 ) {
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
			logDate = sdf.format(startDate);
			alList = auditLogDAO.getAllAuditLogsByLogUserLogDate(logDate, loggedUser);
			if(alList.size() != 0){
				for(Iterator i1 = alList.iterator(); i1.hasNext();){
					AuditLog al = (AuditLog) i1.next();
					grandTotal = grandTotal + Double.valueOf(al.getAl_grand_total());
					auditlogList.add(al);
					}
			}
			
			Long nextDay = startDate.getTime() + (1000 * 60 * 60 * 24);
			startDate.setTime(nextDay);
		}
		
		userList = usersDAO.getAllUsers();
		
		request.getSession().setAttribute("userList", userList);
		request.getSession().setAttribute("auditlogList", auditlogList);
		request.getSession().setAttribute("grandTotal", grandTotal);
		
		startDate.setTime(oldstartdate);
		setDispMode(1);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String viewLogDetailsAction(){
		if (sessionLogout.SessionExpired()) {
			addActionMessage("Session already expired");
			return "sessionExpired";
		}
		
		auditLog = auditLogDAO.getAuditLogById(al_id);
		String[] products = auditLog.getAl_products().split("-");
		for(int a=1; a < products.length;a+=3){
			try {
				System.out.println(products[a]);
				ProductDTO productDTO = new ProductDTO();
				productDTO.setName(products[a]);
				productDTO.setQuantity(Integer.valueOf(products[a+1]));
				productDTO.setSubTotal(products[a+2]);
				productList.add(productDTO);
			} catch (IndexOutOfBoundsException e) {
				break;
			}
		}
		
		
		setDispMode(2);
		return SUCCESS;
	}
	
	public String generateAuditPdfAction(){
		if (sessionLogout.SessionExpired()) {
			addActionMessage("Session already expired");
			return "sessionExpired";
		}
		
		try{
			
			String templatePath = request.getSession().getServletContext().getRealPath("/") + "reporttemplates\\auditlog.jrxml";
			String destinationPath = request.getSession().getServletContext().getRealPath("/") + "reporttemplates";
			auditlogList = (List<AuditLog>) request.getSession().getAttribute("auditlogList");
			Iterator<AuditLog> it = auditlogList.iterator();
			Double grandtotal = new Double(0);
			AuditLog a = new AuditLog();
			while(it.hasNext()){
				a = it.next();
				grandtotal = grandtotal + Double.valueOf(a.getAl_grand_total());
			}
			JasperReport jasperReport;
			JasperPrint jasperPrint;
			HashMap jParam = new HashMap<>();
			jParam.put("grandtotal", grandtotal);
			
			jasperReport = JasperCompileManager.compileReport(templatePath);
			JRBeanCollectionDataSource jbc = new JRBeanCollectionDataSource(auditlogList);
			jasperPrint = JasperFillManager.fillReport(jasperReport, jParam, new JRBeanCollectionDataSource(auditlogList,false));
			JasperExportManager.exportReportToPdfFile(jasperPrint, destinationPath+"\\audit.pdf");
			
			fileStream = new DataInputStream(new FileInputStream(destinationPath+"\\audit.pdf"));
			
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	
	
	public InputStream getFileStream() {
		return fileStream;
	}

	public void setFileStream(InputStream fileStream) {
		this.fileStream = fileStream;
	}

	public List<ProductDTO> getProductList() {
		return productList;
	}

	public void setProductList(List<ProductDTO> productList) {
		this.productList = productList;
	}

	public AuditLog getAuditLog() {
		return auditLog;
	}

	public void setAuditLog(AuditLog auditLog) {
		this.auditLog = auditLog;
	}

	public int getAl_id() {
		return al_id;
	}

	public void setAl_id(int al_id) {
		this.al_id = al_id;
	}

	public boolean isGetToday() {
		return getToday;
	}

	public void setGetToday(boolean getToday) {
		this.getToday = getToday;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getLoggedUser() {
		return loggedUser;
	}

	public void setLoggedUser(String loggedUser) {
		this.loggedUser = loggedUser;
	}

	public List<Users> getUserList() {
		return userList;
	}

	public void setUserList(List<Users> userList) {
		this.userList = userList;
	}

	public List<AuditLog> getAuditlogList() {
		return auditlogList;
	}

	public void setAuditlogList(List<AuditLog> auditlogList) {
		this.auditlogList = auditlogList;
	}

	public int getDispMode() {
		return dispMode;
	}

	public void setDispMode(int dispMode) {
		this.dispMode = dispMode;
	}
	
	

}
